package com.iakuil.app.common.db;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.iakuil.app.common.core.constant.SysConstant;
import com.iakuil.app.common.core.util.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.web.context.request.RequestContextHolder;

import java.util.Date;

/**
 * 审计追踪
 *
 * <p>自动填充创建人、创建时间、修改人和修改时间等审计字段。
 *
 * @author Kai
 * @date 2021/6/23 15:08
 **/
public class AuditTrailHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        Date now = new Date();
        this.strictInsertFill(metaObject, SysConstant.DEFAULT_CREATE_TIME_FIELD, Date.class, now);
        this.strictInsertFill(metaObject, SysConstant.DEFAULT_UPDATE_TIME_FIELD, Date.class, now);

        Long uid = getUserId();
        this.strictInsertFill(metaObject, SysConstant.DEFAULT_CREATE_USER_FIELD, Long.class, uid);
        this.strictInsertFill(metaObject, SysConstant.DEFAULT_UPDATE_USER_FIELD, Long.class, uid);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, SysConstant.DEFAULT_UPDATE_TIME_FIELD, Date.class, new Date());
        this.strictInsertFill(metaObject, SysConstant.DEFAULT_UPDATE_USER_FIELD, Long.class, getUserId());
    }

    private Long getUserId() {
        // 如果是OpenFeign调用，请注意包含Authorization请求头
        return isWeb() ? SecurityUtils.getCurrentUserId() : SysConstant.SYS_USER_ID;
    }

    private boolean isWeb() {
        return RequestContextHolder.getRequestAttributes() != null;
    }
}
